package com.dkm.modules.sys.user.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dkm.commons.BaseController;
import com.dkm.commons.PageQueryParams;
import com.dkm.commons.Response;
import com.dkm.constant.Constant;
import com.dkm.exception.ServiceException;
import com.dkm.modules.sys.user.model.RegisterUserResult;
import com.dkm.modules.sys.user.model.User;
import com.dkm.modules.sys.user.service.UserService;
import com.dkm.modules.wx.card.mapper.CardMapper;
import com.dkm.modules.wx.card.mapper.RechargeRecodMapper;
import com.dkm.modules.wx.card.model.Card;
import com.dkm.modules.wx.card.model.RechargeRecodPO;
import com.dkm.modules.wx.card.model.RechargeRecods;
import com.dkm.modules.wx.card.service.CardService;
import com.dkm.util.IdGen;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static com.dkm.constant.Constant.RECHARGE_RECOD_TYPE_GIVE;
import static com.dkm.constant.Constant.RECHARGE_RECOD_TYPE_SYSTEM;

/**
 * @描述 注册用户管理 --控制器
 * @创建时间 2019/10/6
 * @创建人 yangbin
 */
@Api(tags = {"A7 注册用户管理"})
@RestController
@RequestMapping("/registerUser")
public class RegisterUserController extends BaseController {

    private final static Logger logger = LoggerFactory.getLogger(RegisterUserController.class);
    @Autowired
    private CardService cardService;

    @Autowired
    private CardMapper cardMapper;

    @Autowired
    private UserService userService;

    @Autowired
    RechargeRecodMapper rechargeRecodMapper;

    @ApiOperation("退款")
    @PostMapping("/refundAmount")
    @ApiImplicitParam(paramType = "header", name = "token", value = "身份认证Token")
    public Response refundAmount(@ApiParam("充值记录id") @RequestParam(value = "recordId") Integer recordId,
                                 @ApiParam("退款金额,单位为分") @RequestParam(value = "amount") Integer amount) {

        if (Objects.isNull(recordId) || Objects.isNull(amount) || amount <= 0) {
            throw new ServiceException("充值记录id不能为空,退款金额不能为空不能为0,不能为负数!");
        }

        RechargeRecodPO recodPO = rechargeRecodMapper.selectById(recordId);
        String rechargeNumber = recodPO.getRechargeNumber();
        if (Objects.isNull(recodPO)) {
            throw new ServiceException("充值记录不存在!");
        }
            if (!Constant.RECHARGE_RECOD_TYPE_RECHARGE.equals(recodPO.getType())
                && !Constant.RECHARGE_RECOD_TYPE_SYSTEM.equals(recodPO.getType())
                && !Constant.RECHARGE_RECOD_TYPE_GIVE.equals(recodPO.getType())) {
            throw new ServiceException("只能对充值或赠送类型的记录进行退款操作!");
        }
        // 转换为元
        BigDecimal refundAmount = BigDecimal.valueOf(amount).divide(BigDecimal.valueOf(100));
        if (refundAmount.compareTo(recodPO.getQuantity()) == 1) {
            throw new ServiceException("退款或转账金额不能大于充值金额!");
        }
        User userInfo = getUserInfo();
        Integer changeType = Constant.RECHARGE_RECOD_TYPE_REFUND;
        // 系统充值退款,只退卡金额,因为充值时,充到卡上
        if (RECHARGE_RECOD_TYPE_SYSTEM.equals(recodPO.getType())) {
            Integer cardId = recodPO.getCardId();
            if (Objects.isNull(cardId)) {
                throw new ServiceException("卡充值记录没有卡号!");
            }

            Card card = cardService.selectById(cardId);
            if (Objects.isNull(card)) {
                throw new ServiceException("卡不存在");
            }
            cardService.updateAmountAndRecord(card.getCardNo(), refundAmount.negate(), rechargeNumber, changeType, userInfo);
        }

        // 赠送退款,卡金额账户余额,无需调用微信退款接口
        if (RECHARGE_RECOD_TYPE_GIVE.equals(recodPO.getType())) {
            userService.giveRefundAmount(recodPO, refundAmount, rechargeNumber, changeType, userInfo);
        }

        // 微信充值退款,需调用微信退款接口
        if (Constant.RECHARGE_RECOD_TYPE_RECHARGE.equals(recodPO.getType())) {
            userService.wxRefundAmount(recodPO, refundAmount, rechargeNumber, changeType, userInfo);
        }
        return Response.ok();
    }


    @PostMapping("/refundResult")
    public void refundResult(@RequestBody String xmlData) {

        userService.refundResult(xmlData);
    }

    @ApiOperation("绑定手机号")
    @PostMapping("/bindMobile")
    @ApiImplicitParam(paramType = "header", name = "token", value = "身份认证Token")
    public Response bindMobile(@ApiParam("用户ID") @RequestParam(value = "userId") Integer userId,
                               @ApiParam("手机号") @RequestParam(value = "mobile") String mobile) {

        userService.bindMobile(userId, mobile);

        return Response.ok();
    }

    @ApiOperation("充值记录")
    @GetMapping("/getRechargeRecods")
    @ApiImplicitParam(paramType = "header", name = "token", value = "身份认证Token")
    public Response<IPage<RechargeRecods>> getRechargeRecods(@ApiParam("用户ID") @RequestParam(value = "userId", required = false) String userId,
                                                             @ApiParam("搜索关键字") @RequestParam(value = "keyWord", required = false) String keyWord,
                                                             PageQueryParams p) {
        logger.info("获取充值记录");
        Page<RechargeRecods> page = new Page<>(p.getPageNo(), p.getPageSize());
        Map<String, Object> params = new HashMap<>();
        // 区分开来，在运营端使用
        params.put("userIdInSys", userId);
        params.put("keyWord", keyWord);
        IPage<RechargeRecods> recods = cardService.geRechargeRecods(params, page);
        return Response.ok(recods);
    }

    @ApiOperation("注册用户列表")
    @GetMapping("/getRegisterUser")
    @ApiImplicitParam(paramType = "header", name = "token", value = "身份认证Token")
    public Response getRegisterUser(@ApiParam("用户ID") @RequestParam(value = "userId", required = false) String userId,
                                    @ApiParam("搜索关键字") @RequestParam(value = "keyWord", required = false) String keyWord,
                                    PageQueryParams p) {
        logger.info("注册用户列表");
        Page<RegisterUserResult> page = new Page<>(p.getPageNo(), p.getPageSize());
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("keyWord", keyWord);
        IPage<RegisterUserResult> users = cardService.getRegisterUser(params, page);
        return Response.ok(users);

    }

    @ApiOperation("用户信息")
    @GetMapping("/userInfo")
    @ApiImplicitParam(paramType = "header", name = "token", value = "身份认证Token")
    public Response userInfo() {
        return Response.ok(getUserInfo());
    }
}
